
import axios from 'axios'

import store from '../store'
import conf from '../config/config'
import code from '../config/code'

const request = axios.create({
  baseURL: conf.baseUrl,
  timeout: 5000
})

request.interceptors.request.use(
  config => {
    if (store.getters['User/token']) {
      const tokenName = conf.token_name
      config.headers[tokenName] = store.getters['User/token']
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code !== code.CODE_SUCCESS) {
      console.log(res)

      let errMsg = res.message || '请求失败'
      let time = 1000

      // response.msg => object 模型错误
      // 只取1条错误
      if (typeof errMsg === 'object') {
        const arr = Object.keys(errMsg)
        errMsg = errMsg[arr[0]].join(',')
        time = 3000
        console.log(errMsg)
      }

      if (res.code !== code.CODE_ERROR_CUSTOM) {
        uni.showToast({
          duration: time,
          icon: 'error',
          title: errMsg,
          mask: true
        })
      }

      if (res.code === code.CODE_NOTHING) {
        uni.showToast({
          duration: 1000,
          icon: 'error',
          title: '错误页面',
          mask: true
        })
      }

      if (res.code === code.CODE_TOKEN_EXPIRED) {
        uni.showToast({
          duration: 1000,
          icon: 'error',
          title: '登录过期,请重新登录!',
          mask: true
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/sub_common/user/login'
          })
        }, 500)
      }

    } else {
      return res
    }
  },
  error => {
    console.log('请求错误' + error)

    const { msg } = error.response.data

    return Promise.reject(error)
  }
)

export default request
